package com.baizhi.service.Impl;

import com.baizhi.dao.UserFileDao;
import com.baizhi.entity.T_files;
import com.baizhi.service.UserFIleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.util.List;

@Service
@Transactional
public class UserFIleServiceImpl extends ServiceImpl<UserFileDao, T_files> implements UserFIleService {

    @Autowired
    UserFileDao userFileDao;


    /**
     * 根据用户id查对于文件数据
     */
    public List<T_files> selectByUserID(Integer userId) {

        LambdaQueryWrapper<T_files> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(T_files::getUserId, userId);

        List<T_files> list = this.list(queryWrapper);


        return list;
    }

    /**
     * 更新下载次数
     */
    public void updateDownCounts(T_files byId) {

        Integer num = byId.getDownCounts();
        byId.setDownCounts(num + 1);
        this.updateById(byId);
    }

    /**
     * 文件下载
     */
    public void fileDownLoad(T_files byId, HttpServletResponse response, String openStyle) throws IOException {

        // 文件保存路径
        String realPath = byId.getPath();

        // 文件输入流
        FileInputStream is = new FileInputStream(new File(realPath, byId.getNewFileName()));

        // 选择下载方式、和下载后显示的文件名
        response.setHeader("content-disposition", openStyle + ";fileName="
                + URLEncoder.encode(byId.getOldFileName(), "UTF-8"));

        // 输出流
        ServletOutputStream os = response.getOutputStream();

        // 拷贝
        IOUtils.copy(is, os);

        // 关闭
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }


    /**
     * 删除保存的文件
     */
    public void delete(T_files byId) throws FileNotFoundException {

        String realPath = ResourceUtils.getURL("classpath:").getPath() + "static" + byId.getPath();


        File file = new File(realPath, byId.getNewFileName());
        System.err.println("删除的文件：" + realPath +"/"+ byId.getNewFileName());
        if(file.exists()){
            file.delete();
        }
    }
}
